package com.haoniu.upload.controller;

import com.haoniu.common.core.utils.uuid.UUID;
import com.haoniu.share.domain.Result;
import com.haoniu.upload.service.UploadService;
import com.haoniu.upload.utils.QiniuUtil;
import com.qiniu.storage.model.DefaultPutRet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author shrimpBalls
 * @Date2022/7/18 8:27
 * 概要：
 * 这是一个类
 */
@RestController
@RequestMapping("/document")
@CrossOrigin
public class UploadController {
    @Autowired
    private UploadService uploadService;

    @Autowired
    private QiniuUtil qiniuUtil;

    @RequestMapping("/upload")
    public Result upload(MultipartFile file) {

        if (file.isEmpty()) {
            return Result.error("上传文件不能为空");
        }
        try {
            MultipartFile multipartFile = file;
            BufferedInputStream fileInputStream = new BufferedInputStream(multipartFile.getInputStream());
            String originalFilename = file.getOriginalFilename();
            String fileExtend = originalFilename.substring(originalFilename.lastIndexOf("."));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String yyyyMMddHHmmss = sdf.format(new Date());
            //默认不指定key的情况下，以文件内容的hash值作为文件名
            String fileKey = UUID.randomUUID().toString().replace("-", "") + "-" + yyyyMMddHHmmss + fileExtend;
            Map<String, Object> map = new HashMap<>();
            DefaultPutRet uploadInfo = qiniuUtil.upload(fileInputStream, fileKey);
            map.put("fileName", uploadInfo.key);
            map.put("originName", originalFilename);
            map.put("size", file.getSize());
            //七牛云文件私有下载地址（看自己七牛云公开还是私有配置）
            //map.put("url", "/linfen/qiniu/private/file/" + uploadInfo.key);
            map.put("url", "/linfen/qiniu/file/" + uploadInfo.key);//七牛云公开下载地址
            // log.info("文件：" + JSONObject.toJSONString(map));
            return Result.ok(map);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("上传失败");
        }
    }
}
